<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('事项类型')" prop="itemType">
            <el-select v-model="form.itemType" filterable :placeholder="$t('事项类型')" @change="itemTypeChange">
              <el-option
                v-for="dict in itemTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.itemType === 'DEAL'" :label="$t('项目类型')" prop="projectType">
            <el-select v-model="form.projectType" filterable :placeholder="$t('项目类型')" @change="showVal">
              <el-option
                v-for="dict in projectTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.itemType === 'FUND'" :label="$t('基金类型')" prop="projectType">
            <el-select v-model="form.projectType" filterable :placeholder="$t('基金类型')" @change="showVal">
              <el-option
                v-for="dict in fundTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.projectType === 'DZD'" :label="$t('项目')" prop="moduleId">
            <el-select v-model="form.moduleId" multiple filterable :placeholder="$t('项目')" :clearable="true">
              <el-option
                v-for="dict in dealBaseList"
                :key="dict.id"
                :label="$t(dict.dealName)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.projectType === 'FZD'" :label="$t('基金')" prop="moduleId">
            <el-select v-model="form.moduleId" multiple filterable :placeholder="$t('基金')" :clearable="true">
              <el-option
                v-for="dict in fundBaseList"
                :key="dict.id"
                :label="$t(dict.fundName)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒标题')" prop="reminderTitle">
            <el-input v-model="form.reminderTitle" :placeholder="$t('提醒标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒对象类型')" prop="reminderObjectType">
            <el-select v-model="form.reminderObjectType" filterable :placeholder="$t('提醒对象类型')" @change="reminderObjectTypeChange">
              <el-option
                v-for="dict in reminderObjectTypeConvert"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.reminderObjectType" :span="12">
          <el-form-item :label="$t('提醒对象')" prop="reminderObject">
            <user-select v-if="form.reminderObjectType === 'user'" v-model="form.reminderObject" :placeholder="$t('请选择')" multiple />
            <el-select v-else-if="form.reminderObjectType === 'team' && form.itemType === 'DEAL'" v-model="form.reminderObject" filterable multiple :placeholder="$t('请选择')">
              <el-option
                v-for="dict in dealRoleOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
            <el-select v-else-if="form.reminderObjectType === 'team' && form.itemType === 'FUND'" v-model="form.reminderObject" filterable multiple :placeholder="$t('请选择')">
              <el-option
                v-for="dict in fundRoleOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
            <el-select v-else v-model="form.reminderObject" filterable multiple :placeholder="$t('请选择')">
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒方式')" prop="reminderMode">
            <el-checkbox-group v-model="form.reminderMode">
              <el-checkbox
                v-for="(dict, index) in reminderModeOptions"
                :key="index"
                :label="dict.dictValue"
                border
              >{{ $t(dict.dictLabel) }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
            <el-radio-group v-model="form.reminderFrequency">
              <el-radio
                v-for="dict in reminderFrequencyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col v-if="form.reminderFrequency === 'TIMER'" :span="12">
          <el-form-item :label="$t('定时提醒时间')" prop="timerReminderTime">
            <el-date-picker
              v-model="form.timerReminderTime"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              :placeholder="$t('定时提醒时间')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.reminderFrequency === 'TIMER'" :span="12">
          <el-form-item :label="$t('提前提醒天数')" prop="advanceReminderDay">
            <el-input-number v-model="form.advanceReminderDay" :max="1000" :placeholder="$t('提前提醒天数')" :controls="false" :precision="0" @change="advanceReminderDayChange" />
          </el-form-item>
        </el-col>
        <el-col v-else :span="24">
          <el-form-item :label="$t('频率提醒表达式')" prop="cron">
            <Cron v-model="form.cron" :cron-value.sync="form.frequencyCronValue" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒状态')" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('开启')"
              :inactive-text="$t('关闭')"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('提醒事项内容')" prop="reminderContent">
            <EditorTxt v-model="form.reminderContent" :placeholder="$t('提醒事项内容')" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" data-type="msg_reminder_setting" :btn-show="!otherBtnHide" />
    </el-form>
    <div v-if="!otherBtnHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn has-permi="msg:reminder" />
    </div>
  </div>
</template>

<script>
    import { findDeal } from '@/api/base/deal/dealBase'
    import { findFundFof } from '@/api/fund/fundBase'
    import { saveMsgReminderSetting, getMsgReminderSetting } from '@/api/oa/reminder/msgReminderSetting'
    import { allRole } from '@/api/system/role'
    import Cron from '@/components/Cron'
    import EditorTxt from '@/components/Editor'
    export default {
      components: {
        Cron,
        EditorTxt
      },
      data() {
        var checkAdvanceReminderDay = (rule, value, callback) => {
          if (value < 0) {
            callback(new Error(this.$t('提前提醒天数不能小于0')))
          } else {
            callback()
          }
        }
        return {
          // 项目参与角色
          dealRoleOptions: [],
          // 基金参与角色
          fundRoleOptions: [],
          // 项目下拉数据
          dealBaseList: [],
          // 基金下拉数据
          fundBaseList: [],
          // 项目类型字典
          projectTypeOptions: [],
          // 基金类型字典
          fundTypeOptions: [],
          // 事项类型字典
          itemTypeOptions: [],
          // 提醒对象类型字典
          reminderObjectTypeOptions: [],
          // 提醒方式字典
          reminderModeOptions: [],
          // 提醒频率字典
          reminderFrequencyOptions: [],
          // 角色选项
          roleOptions: [],
          // 是否隐藏其它按钮
          otherBtnHide: false,
          // 表单参数
          form: {
            itemType: undefined,
            projectType: undefined
          },
          // 遮罩层
          loading: false,
          // 表单校验
          rules: {
            itemType: [
              { required: true, message: this.$t('必填信息'), trigger: 'change' }
            ], moduleId: [
              { required: true, message: this.$t('必填信息'), trigger: 'change' }
            ], reminderTitle: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], reminderObjectType: [
              { required: true, message: this.$t('必填信息'), trigger: 'change' }
            ], reminderObject: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], reminderMode: [
              { required: true, message: this.$t('必填信息'), trigger: 'change' }
            ], reminderFrequency: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ],
            timerReminderTime: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
            cron: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
            reminderContent: { required: false, message: this.$t('必填信息'), trigger: 'blur' },
            advanceReminderDay: { validator: checkAdvanceReminderDay, trigger: 'blur' },
            projectType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          }
        }
      },
      computed: {
        reminderObjectTypeConvert() {
          const itemType = this.form.itemType
          if (itemType === 'DAILY') {
            return this.reminderObjectTypeOptions.filter((item) => {
              return item.dictValue !== 'team'
            })
          } else {
            return this.reminderObjectTypeOptions
          }
        }
      },
      created() {
        this.getDicts('reminder_type').then(response => {
          this.itemTypeOptions = response.data
        })
        this.getDicts('reminder_object_type').then(response => {
          this.reminderObjectTypeOptions = response.data
        })
        this.getDicts('reminder_mode').then(response => {
          this.reminderModeOptions = response.data
        })
        this.getDicts('reminder_frequency').then(response => {
          this.reminderFrequencyOptions = response.data
        })
        this.getDicts('reminder_project_type').then(response => {
          this.projectTypeOptions = response.data
        })
        this.getDicts('reminder_fund_type').then(response => {
          this.fundTypeOptions = response.data
        })
        this.getDicts('deal_team_role').then(response => {
          this.dealRoleOptions = response.data
        })
        this.getDicts('fund_team_role').then(response => {
          this.fundRoleOptions = response.data
        })
        allRole().then(response => {
          this.roleOptions = response.data
        })
        findDeal().then(response => {
          this.dealBaseList = response.data
        })
        findFundFof().then(response => {
          this.fundBaseList = response.data
        })
      },
      mounted() {
        this.$bus.$emit('async_done')
      },
      methods: {
        // 初始化数据
        init(data) {
          this.loading = true
          if (data != null && data.id !== undefined) {
            getMsgReminderSetting(data.id).then(response => {
              this.form = response.data
              this.loading = false
            })
          } else {
            this.reset()
            this.loading = false
          }
        },
        // 表单重置
        reset() {
          this.form = {
            id: undefined,
            itemType: undefined,
            projectType: undefined,
            moduleId: undefined,
            reminderTitle: undefined,
            reminderObjectType: undefined,
            reminderObject: undefined,
            reminderMode: [],
            reminderFrequency: 'FREQUENCY',
            timerReminderTime: undefined,
            advanceReminderDay: undefined,
            frequencyCronValue: undefined,
            cron: undefined,
            status: 1,
            reminderContent: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            fileList: []
          }
          this.resetForm('form')
        },
        // 取消按钮
        cancel() {
          this.$parent.$parent.formOpen = false
          this.$parent.$parent.reset()
        },
        // 关闭form页面
        closeForm() {
          // 关闭form页面遮罩层
          this.loading = false
          // 关闭form页面
          this.$parent.$parent.formOpen = false
          // 刷新list页面
          this.$parent.$parent.getList()
        },
        /** 提交按钮 */
        submitForm: function() {
          if (!(this.form.moduleId instanceof Array)) {
            this.$set(this.form, 'moduleId', [])
          }
          if (this.form.moduleId.length < 1) {
            this.form.moduleIdStr = ''
          }
          this.$refs['form'].validate(valid => {
            if (valid) {
              this.loading = true
              saveMsgReminderSetting(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                } else {
                  this.msgError(response.msg)
                }
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
            } else {
              this.locationError(document)
            }
          })
        },
        itemTypeChange(val) {
          this.form.projectType = undefined
          this.form.moduleId = undefined
          if (val === 'DAILY' && this.form.reminderObjectType === 'team') {
            this.form.reminderObjectType = undefined
          }
          if (val === 'FUND' || val === 'DEAL') {
            this.form.reminderObject = undefined
            this.form.reminderObjectType = undefined
          }
        },
        showVal() {
          this.form.moduleId = undefined
          this.$forceUpdate()
        },
        reminderObjectTypeChange() {
          this.form.reminderObject = undefined
        },
        advanceReminderDayChange(val) {
          if (this.form.timerReminderTime) {
            const current = new Date()
            var reminderTime = new Date(this.form.timerReminderTime)
            reminderTime = reminderTime.setDate(reminderTime.getDate() - val)
            console.log(current.getTime(), reminderTime)
            if (reminderTime < current.getTime()) {
              this.$message({
                type: 'warning',
                message: this.$t('提醒日期 - 提前提醒天数不能小于当前日期')
              })
              this.$nextTick(() => {
                this.form.advanceReminderDay = undefined
              })
            }
          }
        }
      }
    }
</script>
